package com.service.bracelet.util;

import com.service.bracelet.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JwtToken生成的工具类
 * JWT token的格式：header.payload.signature
 * header的格式（算法、token的类型）：
 * {"alg": "HS512","typ": "JWT"}
 * payload的格式（用户名、创建时间、生成时间）：
 * {"sub":"wang","created":1489079981393,"exp":1489684781}
 * signature的生成算法：
 * HMACSHA512(base64UrlEncode(header) + "." +base64UrlEncode(payload),secret)
 * Created by macro on 2018/4/26.
 */
public class JwtTokenUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenUtil.class);

    /**
     * 获取token值
     *
     * @param request
     * @return
     */
    public static String getToken(HttpServletRequest request) {
        return request.getHeader(UtilConsts.SECURITY_HEADER);
    }

    /**
     * 获取修改密码时的验证token
     * @param request
     * @return
     */
    public static String getVerifyToken(HttpServletRequest request) {
        return request.getHeader(UtilConsts.SECURITY_VERIFY_TOKEN);
    }

    /**
     * 从token中获取登录用户账号
     *
     * @param request
     * @return
     */
    public static String getUserAccount(HttpServletRequest request) {
        return getUserAccount(getToken(request));
    }

    /**
     * 从token中获取登录用户账号
     */
    public static String getUserAccount(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims != null ? claims.getSubject() : null;
    }

    /**
     * 获取当前登录用户ID
     *
     * @param request
     * @return
     */
    public static int getUserId(HttpServletRequest request) {
        String authToken = getToken(request);
        Claims claims = getClaimsFromToken(authToken);
        return MapUtils.getInteger(claims, UtilConsts.SECURITY_CLAIM_KEY_USERID);
    }

    /**
     * 根据用户信息生成token
     */
    public static String generateToken(User user) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(Claims.SUBJECT, user.getAccount());
        claims.put(UtilConsts.SECURITY_CLAIM_KEY_USERID, user.getId());
        claims.put(UtilConsts.SECURITY_CLAIM_KEY_USERTYPE, user.getUserType());
        claims.put(UtilConsts.SECURITY_CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }

    /**
     * 检查是否管理员
     *
     * @param request
     */
    public static void checkAdmin(HttpServletRequest request) {
        String authToken = getToken(request);
        Claims claims = getClaimsFromToken(authToken);
        int userType = (Integer) claims.get(UtilConsts.SECURITY_CLAIM_KEY_USERTYPE);
        if (userType != UtilConsts.SECURITY_ADMIN_USERTYPE) {
            throw new RuntimeException("没有权限访问当前资源！");
        }
    }

    /**
     * 根据负责生成JWT的token
     */
    public static String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, UtilConsts.SECURITY_HEADER)
                .compact();
    }

    /**
     * 从token中获取JWT中的负载
     */
    private static Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(UtilConsts.SECURITY_HEADER)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            LOGGER.info("JWT格式验证失败:{}", token);
        }
        return claims;
    }
}
